package com.atguigu.srb.core.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.atguigu.common.exception.BusinessException;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.service.DictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
//@CrossOrigin
@Api(tags = "数据字典管理")
@RequestMapping("/admin/core/dict")
@Slf4j
public class AdminDictController {
    @Resource
    RedisTemplate redisTemplate;

    @Autowired
    private DictService dictService;

    @PostMapping("import")
    public R importDate(@ApiParam(value = "Excel文件",required = true) @RequestParam("file") MultipartFile multipartFile){
        try {
            InputStream inputStream = multipartFile.getInputStream();
            dictService.batchImport(inputStream);
            return R.ok().message("数据导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            throw  new BusinessException(ResponseEnum.UPLOAD_ERROR,e);
        }
    }
    @GetMapping("exportData")
    public void exportData(HttpServletResponse response){
        ServletOutputStream outputStream = null;
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition","attachment;filename*=utf-8''"
                    + URLEncoder.encode("学生信息表","utf-8") + ".xlsx");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<ExcelDictDTO> list = dictService.excelDictDTOS();
        EasyExcel.write(outputStream,ExcelDictDTO.class).sheet("数据字典信息表").doWrite(list);
    }

    @GetMapping("getDictListByParentId/{parentId}")
    public R getDictListByParentId(@PathVariable Long parentId){
        List<Dict> list = null;
        list = (List<Dict>) redisTemplate.opsForValue().get("srb:core:dictList:"+parentId);

        if (null == list || list.size() == 0) {
             list = dictService.getDictListByParentId(parentId);
            if (null == list || list.size() ==0){
                redisTemplate.opsForValue().set("srb:core:dictList:"+parentId,new ArrayList<>(),300, TimeUnit.SECONDS);
            }else {
                redisTemplate.opsForValue().set("srb:core:dictList:"+parentId,list);
            }

        }
        return R.ok().data("list", list);
    }
}
